<template>
  <div class="detail-wrap">
    <affix :label="$t('call.callInfo')" class="call-detail">
      <detail-table :curModel="curModel" :callData="currentCallData" :isCall="true" :audioId="audioId" :pauseAudio="pauseAudio" @addCdrBlackList="addCdrBlackList"></detail-table>
    </affix>
    <affix :label="$t('call.callLabelAndSQ')" v-show="isMark">
      <div class="sq-label-wrap">
        <span>{{$t('call.SQLabel')}}:</span>
        <span class="sq-label" v-if="allQSLabel.length <= 0">{{$t('call.noSQLabel')}}</span>
        <span v-else-if="Array.isArray(currentCallData.sqLabelName)" style="margin-left:5px">
          <el-tag v-for="(item,index) in currentCallData.sqLabelName" :key="index" class="SQlabel" type="info" size="small">{{item}}</el-tag>
        </span>
        <span v-else style="margin-left:5px">{{currentCallData.sqLabelName}}</span>
      </div>
      <single-label v-if="!loading && labelType === 'single'" :callLabel="getCallLabel" :flag="flag" :disabled="labelDisabled"  :refreshCallLabel="refreshCallLabel" :checkLabels="currentCallData.LABELS || []" :callSheetId="currentCallData._id"  :showOperaLog="true" ></single-label>
      <multi-label v-if="!loading&& labelType === 'multi'" :callLabel="getCallLabel" :flag="flag" :disabled="labelDisabled" :refreshCallLabel="refreshCallLabel" :checkLabels="currentCallData.LABELS || []" :callSheetId="currentCallData._id"  :showOperaLog="true" :showAdd="showAdd"></multi-label>
    </affix>
    <affix :label="$t('cti.trasferReason')" v-show="currentCallData.TRANSFER_REASON">
      <el-input
        type="textarea"
        :rows="2"
        disabled
        v-model="currentCallData.TRANSFER_REASON">
      </el-input>
    </affix>
    <affix :label="$t('call.ivrTrajectory')" v-show="currentCallData.ivr_contrail&&currentCallData.ivr_contrail.length>0">
      <contrail :ivrData="currentCallData.ivr_contrail" :connectType="currentCallData.CONNECT_TYPE"></contrail>
    </affix>
    <affix :label="$t('call.callHistory')" v-show="currentCallData.call_history&&currentCallData.call_history.list&&currentCallData.call_history.list.length>0">
      <call-history :callHistory="currentCallData.call_history" :currentCallData="currentCallData" :callSheetId="currentCallData.CALL_SHEET_ID"></call-history>
    </affix>
    <affix :label="$t('call.transferContrail')" class="call-detail" v-show="currentCallData.transfer_contrail&&currentCallData.transfer_contrail.length>0">
      <table>
        <tr>
          <td>{{$t('public.time')}}</td>
          <td>{{$t('call.transferFrom')}}</td>
          <td>{{$t('call.transferAction')}}</td>
          <td>{{$t('call.transferTo')}}</td>
        </tr>
        <tr v-for="(item, index) in currentCallData.transfer_contrail" :key="index">
          <td>{{item.beginTime}}</td>
          <td>{{item.transferFrom}}</td>
          <td>{{$t('call.transferToName',{transferToName: item.transferAction})}}</td>
          <td>{{item.transferTo}}</td>
        </tr>
      </table>
    </affix>
  </div>
</template>
<script>
  import Affix from '@/components/ui-modules/affix/Affix'
  import SingleLabel from '@/components/business-modules/call/SingleLabel'
  import MultiLabel from '@/components/business-modules/call/MultiLabel'
  import Contrail from '@/components/business-modules/call/Contrail'
  import CallHistory from '@/components/business-modules/call/CallHistory'
  import DetailTable from './DetailTable.vue'
  import { getCallTimeLength, getAllUseSingleCallLabel, getAllUseMultiCallLabel, isHasFunc, checkHideTel, getSingleOrMultiLabelNameById, deepClone } from '@/utils/m7Utils.js'
  import AudioCommon from '@/components/public-modules/audio'
  function getCallDetail (store, _id, type) {
    let data = {data: _id, type: type}
    return store.dispatch('getSelectedCallInfo', data)
  }
  export default {
    name: 'CallDetail',
    data () {
      return {
        isMark: false,
        labelDisabled: false,
        loading: true,
        labelType: '', // 判断是显示单标签还是多级标签的标志
        allQSLabel: [],
        cancleKeyTag: false,
        currentUrl: '',
        refreshCallLabel: 0,
        showAdd: false,
        flag: '' // 是否是待处理，新增标签时使用和QC用法一致
      }
    },
    props: {
      curModel: { // 判断是否是通话模块
        type: Boolean,
        default: function () {
          return false
        }
      },
      refresh: String,
      pauseAudio: String,
      audioId: String,
      getCurrentCallData: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    components: {
      Affix,
      SingleLabel,
      MultiLabel,
      Contrail,
      AudioCommon,
      DetailTable,
      CallHistory
    },
    computed: {
      currentCallData () { // 解决第一次取不到props的异步数据的问题
        let obj = this.getCurrentCallData || {}
        let agentObj = this.$store.getters.agents[obj.DISPOSAL_AGENT]
        if (agentObj) {
          obj.DISPOSAL_AGENT_show = agentObj.displayName + '[' + agentObj.loginName + ']'
        } else {
          obj.DISPOSAL_AGENT_show = '--'
        }
        obj.STATUS_show = this.getResultNameById(obj.STATUS, 'status') // 处理通话状态名称
        obj.queueName = this.getResultNameById(obj.ERROR_MEMO, 'queues') // 处理技能组名称
        obj.CONNECT_TYPE_show = this.getResultNameById(obj.CONNECT_TYPE, 'callType') // 处理技能组名称
        if (obj.CONNECT_TYPE === 'normal' || obj.CONNECT_TYPE === 'transfer') {
          obj.CALL_NO_SHOW = this.checkHideNum(obj.CALL_NO)
        } else {
          obj.CALL_NO_SHOW = obj.CALL_NO
        }
        if (obj.CONNECT_TYPE === 'dialout' || obj.CONNECT_TYPE === 'dialTransfer') {
          obj.CALLED_NO_SHOW = this.checkHideNum(obj.CALLED_NO)
        } else {
          obj.CALLED_NO_SHOW = obj.CALLED_NO
        }
        obj.satisfaction = this.getInvestigate(obj.INVESTIGATE, obj.CHILD_INVESTIGATE)
        obj.CALL_TIME_LENGTH_show = this.callTimeLen(obj.CALL_TIME_LENGTH)
        obj.RING_TIME_LENGTH_show = this.callTimeLen(obj.RING_TIME_LENGTH)
        obj.queueTimeLen = this.callTimeLen(obj.QUEUE_TIME_LENGTH)
        if (obj.MANYQUEUE_NUMBER) {
          let queueArr = obj.MANYQUEUE_NUMBER.split(';')
          let queueArrName = ''
          for (let i = 0; i < queueArr.length; i++) {
            if (i > 0) {
              queueArrName += ' => '
            }
            queueArrName += this.getResultNameById(queueArr[i], 'queues') // 处理技能组名称
          }
          obj.queueArrName = queueArrName
        } else {
          obj.queueArrName = '--'
        }
        if (obj.REPEAT_CALL) {
          obj.repeatCall = obj.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
        } else {
          obj.repeatCall = '--'
        }
        //处理服务品质多选or单选
        if(Array.isArray(obj.SQ_LABEL)){
          obj.sqLabelName = []
          obj.SQ_LABEL.forEach(item=>{
            obj.sqLabelName.push(getSingleOrMultiLabelNameById(this.allQSLabel, item) || '')
          })
        }else{
          obj.sqLabelName = ''
          obj.sqLabelName = getSingleOrMultiLabelNameById(this.allQSLabel, obj.SQ_LABEL) || ''
        }
        this.refreshCallLabel = Math.random()
        let routeArry = this.$route.path.split('/')
        let tabType = routeArry[3]
        if ((tabType === 'cdr_all' && obj.DISPOSAL_AGENT === this.$store.state.session.user._id) || tabType !== 'cdr_all') { // （全部 && 自己的通话记录） || 来电，去电，待处理
          this.showAdd = true
        } else {
          this.showAdd = false
        }
        return obj
      },
      getCallLabel () {
        let labelType = this.$store.state.call.transCache.callLabelType
//        let allLabel = deepClone(this.$store.state.session.dicMap.callLabel)
        let allLabel = this.$getCache('callLabel')
        if (allLabel === -1) {
          allLabel = []
        }
        let routeArry = this.$route.path.split('/')
        let tabType = routeArry[3]
        if (tabType === 'cdr_all' && (!this.currentCallData.DISPOSAL_AGENT || (this.currentCallData.DISPOSAL_AGENT && this.currentCallData.DISPOSAL_AGENT !== this.$store.state.session.user._id))) { // 所有通话里面不是自己的通话记录不能打标签
          this.labelDisabled = true
        } else {
          this.labelDisabled = false
        }
        if (tabType === 'cdr_pending') { // UNDEAL 质检和通话待处理的打标签去掉处理坐席验证，即：处理坐席不是自己也可以打标签
          this.flag = 'UNDEAL'
        } else {
          this.flag = ''
        }
        let multiObj = this.$store.state.call.transCache.multiLabel
        let singleObj = this.$store.state.call.transCache.singleLabel
        if (multiObj && labelType === 'multi') { // 能取多标签并且状态是多级
          return multiObj
        } else if (singleObj.singleLabel && labelType === 'single') { // 能取单标签并且状态是单级
          return singleObj.singleLabel
        } else { // 取不到标签，重新往call里面存单标签和多标签
          let singleObj = getAllUseSingleCallLabel(allLabel)
          this.$store.commit('call/SET_CALL_SINGLE_LABEL', singleObj)
          let multiObj = getAllUseMultiCallLabel(allLabel)
          this.$store.commit('call/SET_CALL_MULTI_LABEL', multiObj)
          if (labelType === 'single') {
            return singleObj.singleLabel
          } else if (labelType === 'multi') {
            return multiObj
          }
        }
      }
    },
    methods: {
      callTimeLen (time) {
        return getCallTimeLength(time)
      },
      getInvestigate (INVESTIGATE, CHILD_INVESTIGATE) {
//        let options = this.$store.state.session.dicMap.investigate
        let options = this.$getCache('investigate')
        let name = ''
        let childName = ''
        console.log(options)
        for (let i = 0; i < options.length; i++) {
          if (INVESTIGATE === options[i].value) {
            name = options[i].name
            console.log(options[i])
            console.log('CHILD_INVESTIGATECHILD_INVESTIGATE')
            if (options[i].children && options[i].children.length > 0 && CHILD_INVESTIGATE) {
              for (let k = 0; k < options[i].children.length; k++) {
                if (CHILD_INVESTIGATE === options[i].children[k].value) {
                  childName = options[i].children[k].name
                  break
                }
              }
            }
            break
          }
        }
        if (!name) {
          name = INVESTIGATE || '' // 若字典配置被删除就默认显示数字eg:1
        }
        if (!childName) {
          childName = CHILD_INVESTIGATE || ''
        } else {
          childName = '--' + childName
        }
        return name + childName
      },
      getResultNameById (master, type) {
        let current = '--'
        let list = []
        if (type === 'status') {
//          list = this.$store.state.session.dicMap.callStatus
          list = this.$getCache('callStatus')
        } else if (type === 'queues') {
//          list = this.$store.state.session.dicMap.queues
          list = this.$getCache('queues')
        } else if (type === 'callType') {
//          list = this.$store.state.session.dicMap.callType
          list = this.$getCache('callType')
        }
        if (!list) {
          return '--'
        }
        for (let i in list) {
          if (type === 'status') {
            if (list[i].code_value === master) {
              current = list[i].code_name
              break
            }
          } else if (type === 'queues') {
            if (list[i].Exten === master) {
              current = list[i].DisplayName
              break
            }
          } else if (type === 'callType') {
            if (list[i].code_value === master) {
              current = list[i].code_name
              break
            }
          }
        }
        return current
      },
      fetchData () {
        let routeArry = this.$route.path.split('/')
        let _id = routeArry[4]
        this._id = routeArry[4]
        let tabType = routeArry[3]
        this.loading = true
        getCallDetail(this.$store, _id, tabType).then((val) => {
          this.loading = false
        })
      },
      checkHideNum (num) {
        return checkHideTel(num, this.$store.state.session.user)
      },
      addCdrBlackList (phoneNum,type,label) {
        // let numPattern = new RegExp(/^((\d{11,12})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/)
        if (/\D/g.test(phoneNum)) {
          this.$message.error(this.$t('call.phoneNumNoRight'))
          return false
        }
        // 呼入和外呼去掉仅字提示
        let newLabel = ''
        if(type == '1' || type == '2') {
          newLabel = label.substring(1,3)
        } else {
          newLabel = label
        }
        this.blackListConfirm(phoneNum,type,newLabel)
      },
      blackListConfirm(phoneNum,phoneType,label){
        this.$confirm(this.$t('call.blackListConfirmType',{type: label}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let data = {}
          let user = this.$store.state.session.user
          data.PBX = user.pbx
          data.Account = user.account
          data.BlackNum = phoneNum
          let displayName = user.displayName
          let exten = user.exten
          data.Memo = this.$t('customer.memo', {displayName, exten})
          let routeArry = this.$route.path.split('/')
          let tabType = routeArry[3]
          let lastData = {}
          // 当时加入呼入与外呼时掉两次接口
          if(phoneType == '3') {
            let newData = deepClone(data)
            newData.Type = '1'
            newData.phoneType = '3'
            lastData = {data: newData, type: tabType}
            this.$store.dispatch('saveBlackList', lastData)
            let data1 = deepClone(data)
            data1.Type = '2'
            data1.phoneType = '3'
            let lastData1 = {data: data1, type: tabType}
            this.$store.dispatch('saveBlackList', lastData1)
          } else {
            data.Type = phoneType
            data.phoneType = phoneType
            lastData = {data: data, type: tabType}
            this.$store.dispatch('saveBlackList', lastData)
          }
        }).catch(() => {
          console.log('取消')
        })
      },
      // 换行转义
      return2Br(str) {
        return str.replace(/<br\/>/g, '\n');
      },
    },
    watch: {
      refresh (cur, old) {
        if (cur === 'callDetail') {
          this.fetchData()
        }
      },
      currentCallData(){
        this.currentCallData.TRANSFER_REASON = this.return2Br(this.currentCallData.TRANSFER_REASON)
      }
    },
    beforeMount () {
      if (isHasFunc('func_mark_cdr', this.$store.state.session.user)) {
        this.isMark = true // 通话标签权限
      }
      this.fetchData()
      let labelType = this.$store.state.call.transCache.callLabelType
      this.labelType = labelType
//      let sqLabels = this.$store.state.session.dicMap.sqLabels
      let sqLabels = this.$getCache('sqLabels')
      if (!sqLabels) { // 若取到了便不再发送请求
        this.$store.dispatch('getCache', {type: 'sqLabels'}).then((req) => {
          this.allQSLabel = req
        })
      } else {
        this.allQSLabel = sqLabels
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../assets/common.styl'
  .call-detail table
    bors(1px,#ddd)
    width 100%
    border-collapse collapse
    tr
      height 40px
      border-bottom 1px solid #e7e7eb
      td
        padding 10px
        color $cf-gray3
        &:nth-of-type(even)
          color $cf-gray0
    tr:nth-of-type(even) td
      background #f4f5f9
    tr:hover td
      background $c-back
  .call-detail table tr:nth-last-child(1)
    border-bottom none
  .remarks
    border-radius 3px
    width 100%
    margin-top 9px
    box-sizing border-box
    color $cf-gray0
    padding 4px 6px
    background #fafafa
    bors(1px,#ddd)
  .detail-wrap
    color $cf-gray1
  .icon
    cursor pointer
  .table-agent
    max-width 5em
  .sq-label
    padding-left 10px
  .sq-label-wrap
    padding-bottom 16px
  .icon-guanbi
    font-size 12px
    font-weight bold
  .remove-warn
    line-height 34px
  .remove-btn
    text-align right
    margin 0
.SQlabel
  margin-right 10px
</style>
